package com.xxxx.springboot.shiro;

import java.text.SimpleDateFormat;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xxxx.springboot.shiro.config.ResultVO;

@Controller
public class HomeIndexController {

	private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	@GetMapping(value = "/login")
	@ResponseBody
	public String defaultLogin() {
		throw new UnauthenticatedException();
	}

	@PostMapping(value = "/login")
	@ResponseBody
	public ResultVO<String> login(@RequestParam("username") String username, @RequestParam("password") String password,
			@RequestParam("rememberMe") boolean rememberMe) {
		// 从SecurityUtils里边创建一个 subject
		Subject subject = SecurityUtils.getSubject();
		Session session = subject.getSession();
		System.out.println("session有效期为：" + session.getTimeout() / 1000 + "秒");
		System.out.println("登录创建session时间为：" + sdf.format(session.getStartTimestamp()));
		// 在认证提交前准备 token（令牌）
		UsernamePasswordToken token = new UsernamePasswordToken(username, password, rememberMe);
		// 执行认证登陆 这里就是调用realm里面的Authentication方法进行认证
		// try {
		subject.login(token);
		// } catch (UnknownAccountException uae) {
		// return "未知账户";
		// } catch (IncorrectCredentialsException ice) {
		// return "密码不正确";
		// } catch (LockedAccountException lae) {
		// return "账户已锁定";
		// } catch (ExcessiveAttemptsException eae) {
		// return "用户名或密码错误次数过多";
		// } catch (AuthenticationException ae) {
		// return "用户名或密码不正确！";
		// }
		if (subject.isAuthenticated()) {
			return ResultVO.success("登录成功");
		} else {
			token.clear();
			return ResultVO.success("登录失败");
		}
	}

	public static String MD5Pwd(String username, String pwd) {
		// 加密算法MD5
		// salt盐 username + salt
		// 迭代次数
		String md5Pwd = new SimpleHash("MD5", pwd, ByteSource.Util.bytes(username + "salt"), 2).toHex();
		return md5Pwd;
	}

	public static void main(String[] args) {
		System.out.println(HomeIndexController.MD5Pwd("xuxue1", "123"));
	}

	@PostMapping(value = "/logout")
	@ResponseBody
	public ResultVO<String> logout() {
		// 从SecurityUtils里边创建一个 subject
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		return ResultVO.success("成功退出");
	}

}
